package com.mazaiting.imqq.ui.fragment;

import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import butterknife.BindView;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import com.lqr.adapter.LQRAdapterForRecyclerView;
import com.lqr.adapter.LQRViewHolderForRecyclerView;
import com.lqr.recyclerview.LQRRecyclerView;
import com.mazaiting.imqq.R;
import com.mazaiting.imqq.model.bean.Conversation;
import com.mazaiting.imqq.model.bean.NewFriend;
import com.mazaiting.imqq.model.bean.PrivateConversation;
import com.mazaiting.imqq.model.db.manager.NewFriendManager;
import com.mazaiting.imqq.ui.activity.MainActivity;
import com.mazaiting.imqq.ui.base.BaseFragment;
import com.mazaiting.imqq.utils.ImageLoaderFactory;
import com.mazaiting.imqq.utils.TimeUtil;
import java.util.ArrayList;
import java.util.List;

/**
 * 消息
 * A simple {@link Fragment} subclass.
 */
public class MessageFragment extends BaseFragment {

  @BindView(R.id.cvMessage_message_fragment)
  LQRRecyclerView mRecyclerView;
  @BindView(R.id.sw_refresh_message_fragment)
  SwipeRefreshLayout mRefreshLayout;
  /**会话列表适配器*/
  LQRAdapterForRecyclerView<Conversation> mAdapter;
  /**会话列表*/
  List<Conversation> mConversations = new ArrayList<>();

  public MessageFragment() {
    // Required empty public constructor
  }

  @Override protected void initData() {
    mRefreshLayout.setEnabled(true);
    setAdapter();
    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(layoutManager);
    mRecyclerView.setAdapter(mAdapter);
    setListener();
  }

  /**
   * 更新会话
   */
  public void updateConversation() {
    Toast.makeText(getActivity(), "更新", Toast.LENGTH_SHORT).show();
    setConversations();
  }

  /**
   * 设置监听
   */
  private void setListener() {
    // 下拉刷新
    mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override
      public void onRefresh() {
        mRefreshLayout.setRefreshing(true);
        updateConversation();
        if (mRefreshLayout.isRefreshing()){
          mRefreshLayout.setRefreshing(false);
        }
      }
    });
  }

  /**
   * 获取会话列表的数据：增加新朋友会话
   */
  private void setConversations(){
    //添加会话
    List<Conversation> conversationList = new ArrayList<>();
    conversationList.clear();
    //TODO 会话：4.2、查询全部会话
    List<BmobIMConversation> list =BmobIM.getInstance().loadAllConversation();
    if(list!=null && list.size()>0){
      for (BmobIMConversation item:list){
        switch (item.getConversationType()){
          case 1: // 私聊 --BmobIMConversationType.PRIVATE
            conversationList.add(new PrivateConversation(item));
            break;
          case 2: // 群聊 BmobIMConversationType.GROUP
            break;
          default:
            break;
        }
      }
    }
    //添加新朋友会话-获取好友请求表中最新一条记录
    List<NewFriend> friends = NewFriendManager.getInstance(getActivity()).getAllNewFriend();
    //if(friends!=null && friends.size()>0){
    //  conversationList.add(new NewFriendConversation(friends.get(0)));
    //}
    //重新排序
    // Collections.sort(conversationList);
    mAdapter.setData(conversationList);
  }

  /**
   * 设置适配器
   */
  private void setAdapter() {
    if (null == mAdapter){
      mAdapter = new LQRAdapterForRecyclerView<Conversation>(getActivity(),R.layout.item_conversation,mConversations) {
        @Override
        public void convert(LQRViewHolderForRecyclerView helper, final Conversation item, final int position) {
          String avatar = item.getAvatar();
          // 设置头像
          ImageLoaderFactory.getLoader().loadAvatar((ImageView)helper.getView(R.id.iv_recent_avatar_conversation),
              avatar, R.mipmap.header);
          helper.setText(R.id.tv_recent_name_conversation, item.getName())
              .setText(R.id.tv_recent_msg_conversation, item.getLastMessageContent())
              .setText(R.id.tv_recent_time_conversation, TimeUtil.getChatTime(false, item.getLastMessageTime()));

          //查询指定未读消息数
          long unread = item.getUnReadCount();
          if(unread>0){
            helper.setViewVisibility(R.id.tv_recent_unread_conversation, View.VISIBLE);
            helper.setText(R.id.tv_recent_unread_conversation, String.valueOf(unread));
          }else{
            helper.setViewVisibility(R.id.tv_recent_unread_conversation, View.GONE);
          }
          // 开启聊天界面
          //getItem(position).onClick(getActivity());
          helper.getView(R.id.rl_recent_root_conversation).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
              getItem(position).onClick(getActivity());
              ((MainActivity)getActivity()).getBottomTabBar().hideBadge(MESSAGE);
            }
          });
        }
      };
    } else {
      mAdapter.notifyDataSetChanged();
    }
  }

  @Override protected void onMessage() {
    super.onMessage();
    Toast.makeText(getActivity(), "聊天页面更新", Toast.LENGTH_SHORT).show();
    updateConversation();
  }

  @Override protected int getFragmentLayoutId() {
    return R.layout.fragment_message;
  }

  @Override public void onResume() {
    super.onResume();
    updateConversation();
  }
}
